<template>
  <div :id="eId" style="width: 100%; height: 100%"></div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'PieEchart',
  props: {
    dataSource: {
      type: Array,
      default() {
        return [
          { value: 1548, name: 'CityE' },
          { value: 735, name: 'CityC' },
          { value: 510, name: 'CityD' },
          { value: 434, name: 'CityB' },
          { value: 335, name: 'CityA' }
        ]
      }
    },
    eId: {
      type: String,
      default() {
        return 'main'
      }
    }
  },
  data() {
    return {
      myChart: null
    }
  },
  computed: {},
  mounted() {
    this.init()
    // window.onresize = () => {
    //   myChart.resize()
    // }
  },
  methods: {
    init() {
      this.myChart = echarts.init(document.getElementById(this.eId))
      var option = {
        title: {
          show: false
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          bottom: 10,
          left: 'center',
          itemWidth: 12,
          itemHeight: 14,
          textStyle: {
            color: '#ccc',
            fontSize: 14,
            fontFamily: 'Arial Normal'
          },
          data: this.dataSource.map(item => item.name)
        },
        color: ['#0272fc', '#07dbff', '#5b49bc', '#57166c', '#63197c'],
        series: [
          {
            type: 'pie',
            radius: ['35%', '50%'],
            center: ['50%', '40%'],
            label: {
              color: '#ccc',
              formatter: '{d}\n{b}\n{c}',
              fontSize: 14,
              fontFamily: 'Arial Normal'
            },
            data: this.dataSource
          }
        ]
      }

      option && this.myChart.setOption(option)
      let that = this
      setTimeout(() => {
        that.myChart.resize()
      }, 200)
      window.addEventListener('resize', () => {
        setTimeout(() => {
          that.myChart.resize()
        }, 200)
      })
    }
  },
  watch: {
    dataSource() {
      this.init()
    }
  }
}
</script>